package com.evildog.workspace.gateway.handler;


import com.evildog.workspace.common.enums.CommonCustomExceptionDesc;
import com.evildog.workspace.common.util.FeignUtil;
import com.evildog.workspace.gateway.provider.ResponseProvider;
import feign.FeignException;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

/**
 * 异常处理
 * https://blog.csdn.net/u010889990/article/details/82963682
 */
public class ErrorExceptionHandler extends DefaultErrorWebExceptionHandler {

    public ErrorExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                                 ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        CommonCustomExceptionDesc status = CommonCustomExceptionDesc.SERVER_ERROR;
        Throwable error = super.getError(request);
        int code = 500;
        if (error instanceof NotFoundException) {
            code = 400;
            status = CommonCustomExceptionDesc.NOT_FOUND;
        }
        if (error instanceof ResponseStatusException) {
            code = ((ResponseStatusException) error).getStatus().value();
            return ResponseProvider.response(code, buildMessage(request, error));
        }
        // 捕捉FeignException
        if (error instanceof FeignException) {
            return ResponseProvider.response(code, FeignUtil.getExceptionMessage((FeignException) error));
        }
        return ResponseProvider.response(code, status);
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     */
    @Override
    @SuppressWarnings("NullableProblems")
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }


    /**
     * 根据code获取对应的HttpStatus
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return HttpStatus.valueOf((Integer) errorAttributes.get("code")).value();
    }

    /**
     * 构建异常信息
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.path());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        return message.toString();
    }

}
